<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/component/commonTagLib.jsp"%>
<!DOCTYPE html>
<html>
<head>
<title><spring:message code="message.lable.DICguiGeChaKan"/></title>
<%@ include file="/WEB-INF/component/commonCSS.jsp"%>
<!--[if lt IE 9]>
    <script src="lib/js/html5shiv.min.js"></script>
    <script src="lib/js/respond.min.js"></script>
<![endif]-->
</head>
<body class="skin-blue-light sidebar-mini fixed skin-blue-light-frame">
    <section class="content-header">
        <h1><spring:message code="message.lable.DICguiGeChaKan"/></h1>
        <ol class="breadcrumb">
             <li><a href="${ctx}/home.jsp"><i class="fa fa-home"></i><spring:message code="message.lable.first"/></a></li>
            <li class="active"><a href="#"><spring:message code="message.lable.DicManage"/></a></li>
            <li class="active"><a href="#"><spring:message code="message.lable.drugspecDic"/></a></li>
        </ol>
    </section>
    <section class="content">
        <div class=" box box-success">
            <div class="box-body">
            <form action="${ctx}/dicDrugspec/exportExcel.html" id="exportExcel" method="post">
            <input id="fileName" name="fileName" type="hidden" value="<spring:message code="message.lable.drugspecxls"/>" />
            	<div class="input">
					<div class="textalign1"><spring:message code="message.listForm.GuiGeMingCheng"/>：</div>
                    <div class="boxinput">
                        <input type="text" class="textinput" id="txtDrugForm" name="specName" placeholder="<spring:message code="message.listForm.GuiGeMingCheng"/>" />
                    </div>
                    
                    <div class="textalign1"><spring:message code="message.listForm.GuiGeBianMa"/>：</div>
                    <div class="boxinput">
                        <input type="text" class="textinput" id="txtDrugName" name="specCode" placeholder="<spring:message code="message.listForm.GuiGeBianMa"/>" />
                    </div>
                    
                    <div class="textalign1"><spring:message code="message.lable.status"/>：</div>
                    <div class="boxinput">
                        <select id="status" name="status" class="textinput">
                            	<option value="" ><spring:message code="message.select.option"/></option>
	                            <option value="1" ><spring:message code="message.button.start"/></option>
	                            <option value="0" ><spring:message code="message.button.stop"/></option>
                            </select>
                    </div>
                   <div class="textalign" >
                    <button id="selectSpec" type="button" onclick="likeQuery();" class="btn btn-success btn-sm"> <spring:message code="message.button.seachSpacing"/></button>
                	</div>
                </div>
                </form>
            </div>
        </div>
       <table class="jqgrid" id="gridlist"></table>
       <div id="gridpage"></div>
       <div class=" box box-warning bottongroup">
           <ms:btn url="/dicDrugspec/add.html"><label id="addNew" class="btn btn-default btn-sm"><spring:message code="message.button.addSpacing"/></label></ms:btn>
           <ms:btn url="/dicDrugspec/enable.html"> <label id="allStart" class="btn btn-default btn-sm"><spring:message code="message.button.startSpacing"/></label></ms:btn>
           <ms:btn url="/dicDrugspec/disable.html"><label id="allDelete" class="btn btn-default btn-sm"><spring:message code="message.button.stopSpacing"/></label></ms:btn>
			<label onclick="exportExcel();" class="btn btn-default btn-sm"><spring:message code="message.lable.daoChu"/></label>
           
       </div>
      
        <div class="modal fade" id="exampleModal" tabindex="-1" >
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-primary">
                        <button type="button" class="close" data-dismiss="modal" ><span>&times;</span></button>
                        <h5 class="modal-title" id="exampleModalLabel"><spring:message code="message.lable.DICguiGeXinZeng"/></h5>
                    </div>
                    <div class="modal-body">
                  <form>
                    <div class="form-group form-group-xs">
                        <label for="recipient-name" class=" control-label"><spring:message code="message.listForm.yiJiGuiGeBianMa"/>：</label>
                        <div class="">
                        	<input type="text" class="form-control"  id="txtOneID" placeholder="<spring:message code="message.listForm.yiJiGuiGeBianMa"/>">
                        </div>
                    </div>
                    <div class="form-group form-group-xs">
                        <label for="recipient-name" class=" control-label"><spring:message code="message.listForm.yiJiGuiGeMingCheng"/>：</label>
                        <div class="">
                        	<input type="text" class="form-control"  id="txtOneName" placeholder="<spring:message code="message.listForm.yiJiGuiGeMingCheng"/>">
                        </div>
                    </div>
                   <div id="addTwoSpec" style="display:none">
                    <button type="button" id="addDouble" class="btn btn-primary btn-sm"><spring:message code="message.listForm.tianJiaErJiGuiGe"/></button>
                    </div>
                    <div id="twoSpec" style="display:none">
                    <div class="form-group form-group-xs">
                        <label for="recipient-name" class="control-label"><spring:message code="message.listForm.erJiGuiGeBianMa"/>：</label>
                        <div class="">
                            <input type="text" class="form-control" id="txtTwoId" placeholder="<spring:message code="message.listForm.erJiGuiGeBianMa"/>">
                        </div>
                    </div>
                    <div class="form-group form-group-xs">
                        <label for="recipient-name" class=" control-label"><spring:message code="message.listForm.erJiGuiGeMingCheng"/>：</label>
                        <div class="">
                            <input type="text" class="form-control" id="txtTwoName" placeholder="<spring:message code="message.listForm.erJiGuiGeMingCheng"/>">
                        </div>
                   </div>
                    </div>
                </form>
            		</div>
              <div class="modal-footer">
              <input hidden="true" id="spid"/>
              <input hidden="true" id="spfatherid"/>
                  <button type="button" onclick="save();" class="btn btn-primary btn-sm"><spring:message code="message.button.saveSpacing"/></button>
                  <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal"><spring:message code="message.button.closeSpacing"/></button>
              </div>
            </div>
         </div>
      </div>
    </section>
   
    <%@ include file="/WEB-INF/component/commonJS.jsp"%>
    <script type="text/javascript">
    
    //绑定回车
    $('#txtDrugName,#txtDrugForm,#status').bind('keydown', function(event) {
        if (event.keyCode == "13") {        //13 位电脑上回车键的位置代码
            $('#selectSpec').click();
        }
    }); 
  
    $("#txtDrugForm").focus();//加载页面光标在第一个查询框内
    
    	var type = 0;//1新增 ，2修改，3新增二级规格 
    	var editType=0;//1修改一级规格，2修改二级规格
    	var flag = false;
	    var mouseX=0;
	    var mouseY=0;
	    $(document).mousemove(function(e){
			  mouseX=e.pageX;
			  mouseY=e.pageY;
			  var coord=$("#more").offset();
	   		  if((mouseX<coord.left||mouseX>(coord.left+$("#more").width())||mouseY<coord.top||
	   				  mouseY>(coord.top+$("#more").height()))&&(mouseX<(coord.left+$("#more").width())||
	   						  mouseX>(coord.left+$("#more").width()+50)||mouseY<(coord.top+1)||mouseY>(coord.top+24+1))){
	   		  	  $("#more").hide();
	   		  } 
		});
		//停用、启用
		function batchChangeStatus(status) {
			var msg = "";
			var url = "";
            if (status == 1){
                msg = "<spring:message code="message.button.start"/>";
                url = "${ctx}/dicDrugspec/disable.html";
            } else if (status == 0){
                msg = "<spring:message code="message.button.stop"/>";
                url = "${ctx}/dicDrugspec/enable.html";
            }
			var rowIds = $("#gridlist").jqGrid("getGridParam", "selarrrow") || [];
			if (rowIds.length <= 0) {
				$.alert("<spring:message code="message.lable.pleaseSelect"/>"+msg+"<spring:message code="message.listForm.guiGe"/><spring:message code="message.yanZheng.ganTanHao"/>", "warn");
				return;
			}
			var str = "";
            var names = "";
            var count = 0;
                for (var i = 0;i < rowIds.length; i++){
                    var rowdata = $("#gridlist").jqGrid('getRowData', rowIds[i]);
                    if (status == 1){
                        if (rowdata.status == "<spring:message code="message.button.stop"/>"){
                        	var specName = "";
                        	if(rowdata.specName){
                        		specName = rowdata.specName+",";

                        	}else{
                        		specName = rowdata.fatherCodeSpecName+",";
                        	}
                            names += specName+",";
                            str += rowIds[i]+",";
                            count++;
                        }
                    } else if(status == 0) {
                        if (rowdata.status == "<spring:message code="message.button.start"/>"){
                        	var specName = "";
                            if(rowdata.specName){
                                specName = rowdata.specName+",";
                            }else{
                                specName = rowdata.fatherCodeSpecName+",";
                            }
                            names += specName+",";
                            str += rowIds[i]+",";
                            count++;
                        }
                    }
                }
                if (names != ""){
                    names = names.substring(0,names.length-1);
                } else {
                    $.alert("<spring:message code="message.lable.pleaseSelect"/>"+msg+"<spring:message code="message.lable.OKData"/>", "warn");
                    return;
                }
                msg += "<spring:message code="message.lable.yiXia"/><spring:message code="message.listForm.guiGe"/>";
			
			$.HN.message.confirm("<spring:message code="message.lable.OKYES"/>"+msg+"<spring:message code="message.lable.ma"/><br/>"+names, '', '').on(function (e) {
	            if (e) {
	            	if (str.length > 0){
                        str = str.substring(0,str.length-1);
                    }
			var list = [];
			for (var i=0; i<rowIds.length; i++) {
				rowId = rowIds[i];
				list.push({"specId":rowId, "status":status});
			}
			$.post(url, {
				"array" : json.jsonToString(list)
			}, function(result) {
				if (result.success) {
					$.alert("<spring:message code="message.HN.alert.chengGongCaoZuo"/>"+count+"<spring:message code="message.HN.alert.tiaoShuJu"/>", "success");
					$("#gridlist").trigger("reloadGrid");
				} else {
					$.alert(result.msg || "<spring:message code="message.HN.alert.fail"/>", "error");
				}
			}, "json");
	            }
			});
		}
        $(function () {
        	$('#allDelete').click(function(){
        		batchChangeStatus(0);
        	});
        	$('#allStart').click(function(){
        		batchChangeStatus(1);
        	});	
        	
            $('#addNew').click(function () {
            	flag=false;
            	type=1;
            	$("#txtOneID").attr("readonly",false);
            	$("#txtOneName").attr("readonly",false);
            	$("#addTwoSpec").show();
            	$("#twoSpec").hide();
            	$("#spid").val("");
            	$("#spfatherid").val("0");
            	$('.modal-title').html('<spring:message code="message.lable.DICguiGeXinZeng"/>');
            	$('#txtOneID').val("");
				$('#txtOneName').val("");
				$('#txtTwoId').val("");
				$('#txtTwoName').val("");
                $('#exampleModal').modal({
                    keyboard: true
                });
            });
		  
            $("#gridlist").jqGrid({
                url: "dicDrugspecList.html",
                mtype: "POST",
                datatype: "json",
                postData:{"specId":"${specId}"},
                autowidth: true,
                height: 270,
                colNames: ['<spring:message code="message.jqGrid.cz"/>',
                           'specId',
                           '<spring:message code="message.listForm.yiJiGuiGeBianMa"/>',
                           '<spring:message code="message.listForm.yiJiGuiGeMingCheng"/>',
                           '<spring:message code="message.listForm.erJiGuiGeBianMa"/>',
                           '<spring:message code="message.listForm.erJiGuiGeMingCheng"/>',
                           '<spring:message code="message.lable.status"/>'],
                colModel: [
					
					{ name: 'operate', width: 50,sortable: false, align:"left",
						formatter : function(val, opts, rowdata) {
							var specCode = rowdata.specCode || rowdata.fatherCode.specCode;
							var specName = rowdata.specName || rowdata.fatherCode.specName;
							var str = "<ms:btn url='/dicDrugspec/edit.html'><a href=\"javascript:edit('"+rowdata.specId+"','"+rowdata.specCode+"');\" style='background:url(${ctx}/lib/img/icon/icon.png) no-repeat 0px 0px' class='opIcon' title='<spring:message code="message.jqGrid.cz.bianJi"/>'></a></ms:btn>";
							str += "<ms:btn url='/dicDrugspecLog/log.html'><a href='${ctx}/dicDrugspecLog/log.html?specId="+rowdata.specId+"&specCode="+specCode+"&specName="+specName+"' style='background:url(${ctx}/lib/img/icon/icon.png) no-repeat -120px 0px' class='opIcon' title='<spring:message code="message.jqGrid.cz.weiHuJiLu"/>'></a></ms:btn>";
							   if(!rowdata.specCode ){							    
								  str += "<ms:btn url='/dicDrugspec/addTwo.html'><a href='javascript:addTwoSpec(\""+rowdata.specId+"\",\""+rowdata.fatherCode.specCode+"\",\""+rowdata.fatherCode.specName+"\")'  style='background:url(${ctx}/lib/img/icon/icon.png) no-repeat -140px 0px' class='opIcon' title='<spring:message code="message.jqGrid.cz.xinZengErJiGuiGe"/>'></a></ms:btn>";
							   }	
							
							//str+="<div id='"+rowdata.specId+"d' onmouseover=\"over('"+rowdata.specId+"','"+rowdata.specCode+"','"+rowdata.fatherCode.specCode+"','"+rowdata.fatherCode.specName+"');\"  style='height:24px;width:50px;margin:0 ;padding:0 ;float:left;line-height:24px'><a>更多...</a></div></div>";
					    	return str;
						}
					},
                    { name: 'specId',hidden:true, width: 80,align:"center",sortable: false},
                    { name: 'fatherCodeSpecCode', width: 80,align:"center",sortable: false,formatter:function(cellvalue, options, row){if(row.fatherCode != null){ return row.fatherCode.specCode; }else{ return row.specCode; }}},
                    { name: 'fatherCodeSpecName', width: 140,align:"center",sortable: false,formatter:function(cellvalue, options, row){if(row.fatherCode!=null){ return row.fatherCode.specName; }else{ return row.specName; }} },
                    { name: 'specCode', width: 100,align:"center",sortable: false,formatter:function(cellvalue, options, row){if(row.fatherCode!=null){ return row.specCode; }else{ return ""; }} },
                    { name: 'specName', width: 140,align:"center",sortable: false ,formatter:function(cellvalue, options, row){if(row.fatherCode!=null){ return row.specName; }else{ return ""; }} },
                    { name: 'status', width: 30 , align: 'center',sortable: false,
                    	cellattr:function (rowId, val, rawObject, cm) {
                            if(val == '停用'){
                                return 'style="color:red"';
                            }
                        },
                    	formatter : function(val, opts, rowdata) {
                    		var strSta = "";
                    		if(rowdata.status == 1){
                    			strSta += "<spring:message code="message.button.start"/>";
                    		}else{
                    			strSta += "<spring:message code="message.button.stop"/>";
                    		}
                    		return strSta;
                    	}
                    }
                ],
                rowNum: 20,
                rowList: [10, 20, 50,100],
                rownumbers: true,
                pager: "#gridpage",
                viewrecords: true,
                multiselect: true, 
                gridComplete:function(){
                    //序号列宽度自适应（参数为jqgridID）
                    autoRNWidth("gridlist");
                    //数据只有一条时默认选中（参数为jqgridID）
                    selectByOneData("gridlist");
                },
                caption: "<spring:message code="message.list.drugspecDiclist"/>",
                jsonReader: {
                    repeatitems: false,
                    id: "specId"
                }
            });
            $("#gridlist").jqGrid('navGrid', '#gridpage', { add: false, edit: false, del: false, search: false, refresh: false });
          
           
        });
        //保存
        function save(){
        	var fspecCode="";
        	var fspecName="";
        	 var specCode = "";
	          var specName = "";
        	if(type==1){
        		if(flag){
        			if (!validate2()) {
    	    			return;
    	    		}
        			 fspecCode = $("#txtOneID").val();
			         fspecName = $("#txtOneName").val();
			         specCode = $("#txtTwoId").val();
			         specName = $("#txtTwoName").val();
			         if(fspecCode==specCode){
			        	 $.alert("<spring:message code="message.yanZheng.liangGe"/><spring:message code="message.yanZheng.bianMa"/><spring:message code="message.yanZheng.buNengChongFu"/>", 'warn');
			        	 return;
			         }
			         if(fspecName==specName){
			        	 $.alert("<spring:message code="message.yanZheng.liangGe"/><spring:message code="message.yanZheng.mingChen"/><spring:message code="message.yanZheng.buNengChongFu"/>", 'warn');
			        	 return;
			         }
        		}else{
        			if (!validate1()) {
    	    			return;
    	    		}
        			
        			 specCode = $("#txtOneID").val();
			         specName = $("#txtOneName").val();
        		}
        	}
			if(type==2){
			       if(editType==1){
			    	   if (!validate1()) {
	    	    			return;
	    	    		}
			    	   specCode = $("#txtOneID").val();
			           specName = $("#txtOneName").val();
			       }
				   if(editType==2){
					   if (!validate2()) {
	    	    			return;
	    	    		}
					   specCode = $("#txtTwoId").val();
			           specName = $("#txtTwoName").val();
			       }
			}
			if(type==3){
				if (!validate2()) {
	    			return;
	    		}
				
				specCode = $("#txtTwoId").val();
		        specName = $("#txtTwoName").val();
			}
			 var specId = $("#spid").val();
        	 var fatherId = $("#spfatherid").val();
        	 
      	  		$.HN.message.confirm('<spring:message code="message.HN.alert.OkSaveYESorNO"/>', '', '').on(function (e) {
	               if (e) {
	            	   var url = "${ctx}/dicDrugspec/add.html";
	                    if(specId !=null && specId != ""){      
	                        url = "${ctx}/dicDrugspec/edit.html";               }
	               	$.ajax({
	           		   type: "POST",
	           		
	           		   url: url,
	           		   //data: "specCode="+specCode+"&specName="+specName+"&specId="+specId+"&fatherId="+fatherId,
	           		   data:{
	           			    specCode:specCode,
	           			    specName:specName,
	           			    specId:specId,
	           			    fatherId:fatherId,
	           			    fspecCode:fspecCode,
	           			    fspecName:fspecName
	           		   },
	           		   dataType:"json",
	           		   success: function(result){
	           			   if(result.success){
	           				$.alert("<spring:message code="message.HN.alert.success"/>", "success");
	           				   $("#gridlist").jqGrid('setGridParam',{page:1}).trigger("reloadGrid");
	           				$('#exampleModal').modal('hide');
	           			   }else{
	           				$.alert(result.msg || "<spring:message code="message.HN.alert.fail"/>", "error");
	                			   }
	                		   }
	                	});
	                }
           	 });
        }
        //编辑
        function edit(specId,specCode){
        	type=2;
        	$("#txtOneID").attr("readonly",false);
        	$("#txtOneName").attr("readonly",false);
        	$("#addTwoSpec").hide();
        	$('.modal-title').html('<spring:message code="message.lable.DICguiGeBianJi"/>');
        	$("#spfatherid").val("");
        	$("#spid").val(specId);
        	$('#exampleModal').modal({
                keyboard: true
            });
        		$.post("${ctx}/dicDrugspec/initEdit.html", {
        			specId : specId
        		},
        		 		
        		function(result) {
        			if (result.success) {
        				var obj = result.rows;
        				if(obj[0]){
        					$("#txtOneID").val(obj[0]);
            				$("#txtOneName").val(obj[1]);
            				$("#txtTwoId").val(obj[2]);
            				$("#txtTwoName").val(obj[3]);
            				$("#twoSpec").show();
            				$("#txtOneID").attr("readonly",true);
            	        	$("#txtOneName").attr("readonly",true);
            	        	editType=2;
        				}else{
        					$("#txtOneID").val(obj[2]);
            				$("#txtOneName").val(obj[3]);
            				$("#txtTwoId").val("");
            				$("#txtTwoName").val("");
            				$("#twoSpec").hide();
            				editType=1;
        				}
        				
        			}else{
        				$("#txtOneID").val("");
        				$("#txtOneName").val("");
        				$("#txtTwoId").val("");
        				$("#txtTwoName").val("");
        				$("#twoSpec").hide();
        				$.alert(result.msg || "<spring:message code="message.HN.alert.fail"/>", "error");
        			}
        			
        		}, "json");
        }
        //新增二级
        function addTwoSpec(fatherId,specCode,specName){
        	type=3;
        	$("#txtOneID").attr("readonly",true);
        	$("#txtOneName").attr("readonly",true);
        	$("#addTwoSpec").hide();
        	$("#twoSpec").show();
        	$('.modal-title').html('<spring:message code="message.listForm.tianJiaErJiGuiGe"/>');
        	$("#txtOneID").val(specCode);
        	$("#txtOneName").val(specName);
        	$('#txtTwoId').val("");
			$('#txtTwoName').val("");
        	$("#spid").val("");
        	$("#spfatherid").val(fatherId);
        	$('#exampleModal').modal({
                keyboard: true
            });
        }
        //查询
        function likeQuery(){
        	var specCode  = $("#txtDrugName").val();
       	    var specName = $("#txtDrugForm").val();
       	    var status = $("#status").val();
       		 $("#gridlist").jqGrid('setGridParam', { 
       			url: "${pageContext.request.contextPath}/dicDrugspec/dicDrugspecList.html", 
       			mtype: "POST",
       		    datatype:'json',
		        postData:{
					"specCode":specCode,
					"specName":specName,
					"status":status},
       			page: 1 
       		}).trigger("reloadGrid");
        }
         function validate1() {
     		var specCode = $.trim($("#txtOneID").val());
     		if (specCode == null || specCode == "") {
     			$.alert("<spring:message code="message.yanZheng.qingShuRu"/><spring:message code="message.listForm.yiJiGuiGeBianMa"/><spring:message code="message.yanZheng.ganTanHao"/>", "warn");
     			return false;
     		}
     		
     		var specName = $.trim($("#txtOneName").val());
     		if (specName == null || specName == "") {
     			$.alert("<spring:message code="message.yanZheng.qingShuRu"/><spring:message code="message.listForm.yiJiGuiGeMingCheng"/><spring:message code="message.yanZheng.ganTanHao"/>", "warn");
     			return false;
     		}

     		return true;
     	}
     	function validate2() {
    		var specCode = $.trim($("#txtTwoId").val());
    		if (specCode == null || specCode == "") {
    			$.alert("<spring:message code="message.yanZheng.qingShuRu"/><spring:message code="message.listForm.erJiGuiGeBianMa"/><spring:message code="message.yanZheng.ganTanHao"/>", "warn");
    			return false;
    		}
    		
    		var specName = $.trim($("#txtTwoName").val());
    		if (specName == null || specName == "") {
    			$.alert("<spring:message code="message.yanZheng.qingShuRu"/><spring:message code="message.listForm.erJiGuiGeMingCheng"/><spring:message code="message.yanZheng.ganTanHao"/>", "warn");
    			return false;
    		}

    		return true;
    	}
     	
     	$("#addDouble").click(function(){
     		 if (!validate1()) {
	    			return;
	    	}
     		$.post("${ctx}/dicDrugspec/checkRepeat.html", {
				specCode : $("#txtOneID").val(),
				specName : $("#txtOneName").val()
			}, function(result) {
				if (result.success) {
					flag = true;
					$("#twoSpec").show();
					$("#addTwoSpec").hide();
					$("#txtOneID").attr("readonly",true);
		        	$("#txtOneName").attr("readonly",true);
				} else {
					$.alert(result.msg || "<spring:message code="message.HN.alert.fail"/>", "error");
				}
			}, "json");
     	});
     	
     	function exportExcel(){
     		$.HN.message.confirm('<spring:message code="message.lable.OKExport"/>&nbsp;<spring:message code="message.lable.drugspecxls"/>&nbsp;<spring:message code="message.lable.ma"/>', '', '').on(function (e) {
	               if (e) {
	            	  $("#exportExcel").submit();
			
	               }
          	 }); 
          	
     	}
    </script>
</body>
</html>